package com.xkdx.guangguang.fragment.shopunitproduct;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.my.pay.TCPSocketCallback;
import com.xkdx.guangguang.fragment.my.pay.TCPSocketConnect;
import com.xkdx.guangguang.fragment.my.setup.SetUpIpFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.ProductInfo;
import com.xkdx.guangguang.util.DialogFactory;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class UnitProductInfoFragment extends BaseFragment implements
		OnClickListener, TCPSocketCallback {
	private View proview;
	private ProductInfo product = new ProductInfo();
	private ImageView logo, tjdd, back;

	private Button sub, add;
	private TextView name, price, num, istip;
	private TextView ts_num;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.shop_empty)
			.showImageForEmptyUri(R.drawable.shop_empty)
			.showImageOnFail(R.drawable.shop_empty).resetViewBeforeLoading()
			.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY)
			.bitmapConfig(Bitmap.Config.RGB_565).build();
	private SharePrefenceUtil sp_pos;
	private SharePrefenceUtil sp_user;

	private String normal_trace;
	private int count = 1;
	private String productID;

	private UnitProductAction unitProductAction;
	private UnitProductModule unitProductModule;
	private UnitProductPresistence unitProductPresistence;

	private String mac_address; // mac地址
	private String pos_trace; // 最终流水号,自增数，流水号

	private TCPSocketConnect connect = null;
	private Dialog dialog;
	private String posresultgetmac;
	private static final String TYPE_MAC = "QueryMac";
	private static final String QUERYMAC = "MACQUERY";
	private String ip;
	public static boolean isUnitBack = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		productID = getArguments().getString("productID");
		sp_pos = new SharePrefenceUtil(getActivity(), IConstants.SP_POS);
		sp_user = new SharePrefenceUtil(getActivity(), IConstants.SP_USER);
		normal_trace = sp_pos.getNormalTrace();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (isUnitBack) {
			getFragmentManager().popBackStack();
		}
		proview = inflater.inflate(R.layout.shop_unit_productintro, container,
				false);
		initViwe(proview);
		showLoading();
		// setValues();
		return proview;
	}

	/**
	 * 初始化值
	 */
	private void setValues() {
		if (product != null) {
			imageLoader.displayImage(product.getPicturePath(), logo, options);
			name.setText(product.getProductName());
			String price1 = String.valueOf(Float.parseFloat(product
					.getProductPrice()) / 100);
			price.setText("¥" + price1 + "元");
			num.setText("已售" + product.getExChange_Num() + "笔");
			ts_num.setText(count + "");

		}
	}

	private void initViwe(View view) {
		logo = (ImageView) view.findViewById(R.id.shop_unit_logo);
		back = (ImageView) view.findViewById(R.id.product_detail_back);
		tjdd = (ImageView) view.findViewById(R.id.im_product_tjdd);
		add = (Button) view.findViewById(R.id.btn_product_add);
		sub = (Button) view.findViewById(R.id.btn_product_sub);
		name = (TextView) view.findViewById(R.id.shop_unitdetail_name);
		price = (TextView) view.findViewById(R.id.shop_unitdetail_price);
		num = (TextView) view.findViewById(R.id.shop_unitdetail_exchangenum);
		ts_num = (TextView) view.findViewById(R.id.tv_goods_number_show);
		istip = (TextView) view.findViewById(R.id.tv_inavaliable);

		back.setOnClickListener(this);
		tjdd.setOnClickListener(this);
		add.setOnClickListener(this);
		sub.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.product_detail_back:
			getFragmentManager().popBackStack();
			break;
		case R.id.im_product_tjdd: // 提交订单
			if (product.getRemain_Num().equals("0")) {
				tjdd.setVisibility(View.GONE);
				istip.setVisibility(View.VISIBLE);
			} else {

				int result_num = Integer.parseInt(ts_num.getText().toString());
				int unit_price = Integer.parseInt(product.getProductPrice());
				int sum = unit_price * result_num;

				product.setOrder_Num(result_num + "");
				product.setProductTotalPrice(sum + "");

				String type = sp_user.getVerifyType();

				// if ((type.equals("2") || type.equals("3")){
				// && sp_user.getShopIds().contains(IConstants.POS_SHOPID)) { //
				// 系统管理员或商家,订单号需要mac地址形式
				if (type.equals("2") || type.equals("3")) {
					pos_trace = sp_pos.getPosTrace();
					mac_address = sp_pos.getPosMac();
					// mac_address = "1234567890";
					ip = sp_pos.getPosIP();
					if (mac_address.equals("")) {

						if (TextUtils.isEmpty(sp_pos.getPosIP())) {
							SetUpIpFragment setUpIpFragment = new SetUpIpFragment();
							FragmentTransaction ft6 = getFragmentManager()
									.beginTransaction();
							ft6.replace(R.id.fragment, setUpIpFragment);
							ft6.addToBackStack(null);
							ft6.commit();
						} else {
							dialog = DialogFactory.creatRequestDialog(
									getActivity(), "正在获取mac地址,请耐心等待...");
							dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
							dialog.show();

							PosRequest();
						}

					} else { // mac地址不为空
						String traceStr = pos_trace.substring(12);
						int lastSixnum = Integer.parseInt(traceStr);
						lastSixnum = lastSixnum + 1;
						String tracelastSixNum = String.format("%06d",
								lastSixnum);
						String trace = mac_address + tracelastSixNum;

						product.setProductPosTrace(trace + "");

						FragmentTransaction ft = getFragmentManager()
								.beginTransaction();
						OrderProductInfoFragment map = new OrderProductInfoFragment();
						Bundle b1 = new Bundle();
						b1.putSerializable("orderproduct", product);
						map.setArguments(b1);
						ft.replace(R.id.fragment, map);
						ft.addToBackStack(null);
						ft.commit();
					}

				} else { // 普通用户 订单号非mac地址形式
					int countNum = Integer.parseInt(sp_pos.getNormalTrace()) + 1;
					product.setProductPosTrace(countNum + "");
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					OrderProductInfoFragment map = new OrderProductInfoFragment();
					Bundle b1 = new Bundle();
					b1.putSerializable("orderproduct", product);
					map.setArguments(b1);
					ft.replace(R.id.fragment, map);
					ft.addToBackStack(null);
					ft.commit();

				}

			}
			break;
		case R.id.btn_product_add:
			count++;
			ts_num.setText(count + "");
			break;
		case R.id.btn_product_sub:
			if (count >= 2) {
				count--;
			} else {
				count = 1;
			}

			ts_num.setText(count + "");
			break;
		}
	}

	/**
	 * pos机支付
	 */
	private void PosRequest() {
		connect = new TCPSocketConnect(this);

		connect.setAddress(ip, IConstants.POS_PORT);
		new Thread(connect).start();

	}

	@Override
	public void findView() {

	}

	@Override
	public void setOnClick() {

	}

	@Override
	public void showLoading() {
		if (dataLoadDialog != null && !(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
		}
		unitProductAction = new UnitProductAction(productID);
		unitProductModule = new UnitProductModule();
		unitProductPresistence = new UnitProductPresistence(this);
		((ManagerActivity) getActivity())
				.addCurrentTask(unitProductPresistence);
		unitProductPresistence.setActitons(unitProductAction);
		unitProductPresistence.setModule(unitProductModule);
		unitProductPresistence.execute();

		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (unitProductPresistence != null) {
					unitProductPresistence.cancel(true);
					getActivity().finish();
				}

			}
		});
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {

		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (map.containsKey("0")) {
			product = unitProductModule.info;
			setValues();
		} else {

		}
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {

	}

	@Override
	public void tcp_connected() {
		handler.sendEmptyMessage(1);
	}

	@Override
	public void tcp_receive(String result) {
		try {

			posresultgetmac = result;

		} catch (Exception e) {
			e.printStackTrace();
		}
		handler.sendEmptyMessage(2);
	}

	@Override
	public void tcp_disconnect() {
		handler.sendEmptyMessage(3);
	}

	@Override
	public void tcp_closeconnect() {
		handler.sendEmptyMessage(4);

	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 1:

				Toast.makeText(getActivity(), "连接成功!", 0).show();
				String queryMacStr = sendRequest(TYPE_MAC); // 对应消息体
				int qmLength = queryMacStr.length();
				String headqmMessage = TentoSixteen(qmLength); // 对应消息头
				byte[] head_byte = new byte[2]; // 对应消息头字节数 固定为2
				head_byte = IConstants.hexStringToBytes(headqmMessage);

				connect.write(head_byte); // 发送
				connect.writeBody(queryMacStr);
				connect.writeBody("\r\n");

				break;
			case 2:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}

				/**
				 * 解析返回数据
				 */
				JsonParse(posresultgetmac);

				break;

			case 3:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}

				Toast.makeText(getActivity(), "pos连接失败，请检查网络连接,重新获取mac地址!", 0)
						.show();

				break;

			case 4:
				if (dialog != null && dialog.isShowing()) {
					dialog.dismiss();
				}
				Log.i("pay", "关闭连接");
				break;

			case 5:
				if (getActivity() != null) {
				Toast.makeText(getActivity(), "mac地址获取失败，请重新获取", 0).show();
				}
				break;

			case 6:
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				OrderProductInfoFragment map = new OrderProductInfoFragment();
				Bundle b1 = new Bundle();
				b1.putSerializable("orderproduct", product);
				map.setArguments(b1);
				ft.replace(R.id.fragment, map);
				ft.addToBackStack(null);
				ft.commitAllowingStateLoss();
				break;
			}
		}
	};

	protected String TentoSixteen(int queryLength) {
		if (queryLength > 0) {
			String result = Integer.toHexString(queryLength);
			int len = result.length();
			StringBuffer sb = null;

			while (len < 4) {
				sb = new StringBuffer();
				sb.append("0").append(result);// 左(前)补0
				result = sb.toString();
				len = result.length();
			}

			return result;
		} else {
			return "0000";
		}

	}

	protected void JsonParse(final String resultShow2) {

		new Thread() {
			public void run() {
				JSONObject obj;
				try {

					int pos = resultShow2.indexOf("{");
					String finalResult = resultShow2.substring(pos);
					obj = new JSONObject(finalResult);

					String code = obj.getString("rescode");
					if (!(code.equals("00"))) {
						handler.sendEmptyMessage(5);

					} else { // mac地址获取成功 ,本地保存

						sp_pos.setPosMac(obj.getString("mac"));

						mac_address = sp_pos.getPosMac();

						String traceStr = pos_trace.substring(12);
						int lastSixnum = Integer.parseInt(traceStr);
						lastSixnum = lastSixnum + 1;
						String tracelastSixNum = String.format("%06d",
								lastSixnum);
						String trace = mac_address + tracelastSixNum;

						product.setProductPosTrace(trace + "");
						handler.sendEmptyMessage(6);

					}
				} catch (JSONException e) {

				}
			};
		}.start();

	}

	protected String sendRequest(String type) {
		String mainBody = new String();

		if (type.equals(TYPE_MAC)) {

			mainBody = CreateMacRequest(QUERYMAC);

		}
		return mainBody.toString();
	}

	private String CreateMacRequest(String mac) {
		String cmdStr = mac;
		StringBuffer sbuff = new StringBuffer();
		sbuff.append("{\"cmd\":\"");
		sbuff.append(cmdStr);
		sbuff.append("\"}");
		return sbuff.toString();

	}

}
